<template>
  <div>
    <el-card class="product-info purchase_card" shadow="never">
      <span slot="header">定标商品信息</span>
      <BasicTable
        ref="multipleTable"
        :show-select-col="false"
        :show-pagination="false"
        :show-ActionCol="false"
        :show-total="false"
        :tableMaxHeight="600"
        :rowHeight="43"
        :loading="tableInfo.loading"
        :data-source="tableInfo.list"
        :columns="tableInfo.columns"
        showSummary
        :summaryMethod="summaryMethod"
      />
      <div class="user-info">
        <span>定标人：{{ userInfo.targetUser }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>定标人公司：{{ userInfo.targetCompany }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>定标时间：{{userInfo.targetDate}}</span>
      </div>
      <el-row type="flex" justify="center">
        <el-button size="mini" type="primary" @click="handleBackHome">返回</el-button>
        <el-button size="mini" type="primary" @click="handleBackQuotePage">上一步</el-button>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import BasicTable from '@/pages/sourcing/components/BasicList';
import { queryCalibrationDetailService } from '@api/sourcing/selfPurchaseInquiry'
import { BID_VIEW_COLUMNS } from '../constants'
import { toFixedCustomize } from '@/utils/bizUtils'

export default {
  // 自进货定标信息
  components: {
    BasicTable,
  },
  data () {
    return {
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      userInfo: {
        targetUser: '',
        targetCompany: '',
        targetDate: '',
      }
    }
  },
  computed: {
    selfPurchaseBillId () {
      return this.$route.query.selfPurchaseBillId
    },
  },
  mounted () {
    this.queryCalibrationInfo();
  },
  methods: {
    handleBackHome () {
      this.$router.push({ name: 'selfPurchase' })
    },
    handleBackQuotePage () {
      this.$router.push({ name: 'selfPurchaseQuotationInfo', query: { selfPurchaseBillId: this.selfPurchaseBillId, isReadOnly: true } })
    },
    // 初始化表头
    initTableColumns () {
      this.tableInfo.columns = _.cloneDeep(BID_VIEW_COLUMNS)
    },
    // 获取定标详情
    async queryCalibrationInfo () {
      const params = {
        selfPurchaseBillId: this.selfPurchaseBillId,
      }
      const res = await queryCalibrationDetailService(params, state => { this.tableInfo.loading = state })
      if (res) {
        const { targetCompany, targetDate, targetUser, skuVoList } = res.data;
        this.userInfo = {
          targetCompany,
          targetDate,
          targetUser,
        }
        this.initTableData(skuVoList);
      }
    },
    // 初始化表格数据
    initTableData (skuList) {
      this.tableInfo.list = [];
      this.initTableColumns();
      skuList.forEach((ele, oneIndex) => {
        const curRow = {
          ...ele
        };
        ele.supplierQuoteList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        this.tableInfo.list.push(curRow);
      });
    },
    pushItem (oneIndex, curRow, item, index) {
      // 将行内动态列的信息，平铺到行
      const tag = item.supplierCode;
      curRow[`supplierName_${tag}`] = item.supplierName;
      curRow[`supplierCode_${tag}`] = item.supplierCode;
      curRow[`invoiceTypeStr_${tag}`] = item.invoiceTypeStr;
      curRow[`belongDepartmentName_${tag}`] = item.belongDepartmentName;
      curRow[`skuNum_${tag}`] = item.skuNum;
      curRow[`unitPrice_${tag}`] = item.unitPrice;
      curRow[`costPrice_${tag}`] = item.costPrice;
      curRow[`skuPrice_${tag}`] = item.skuPrice;
      curRow[`workableArrivalTime_${tag}`] = item.workableArrivalTime;
      curRow[`priceExpireTime_${tag}`] = item.priceExpireTime;
      curRow[`priceExpTypes_${tag}`] = item.priceExpTypes;
      curRow[`recommendSupplierCode_${tag}`] = item.recommendSupplierCode;
      curRow[`recommendSupplierName_${tag}`] = item.recommendSupplierName;
      curRow[`priceExpReasonList_${tag}`] = item.priceExpReasonList;
      curRow[`productCenterPrice_${tag}`] = item.productCenterPrice;
      curRow[`productCenterCostPrice_${tag}`] = item.productCenterCostPrice;
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        this.tableInfo.columns.push({
          label: item.supplierName,
          prop: item.supplierCode,
          children: [
            {
              label: '归属中心',
              prop: `belongDepartmentName_${tag}`,
            },
            {
              label: '发票类型',
              prop: `invoiceTypeStr_${tag}`,
            },
            {
              label: '中标数量',
              prop: `skuNum_${tag}`,
            },
            {
              label: '进价',
              prop: `unitPrice_${tag}`,
            },
            {
              label: '成本价',
              prop: `costPrice_${tag}`,
            },
            {
              label: '中标金额',
              prop: `skuPrice_${tag}`,
            },
            {
              label: '供货进价',
              prop: `productCenterPrice_${tag}`,
            },
            {
              label: '供货成本价',
              prop: `productCenterCostPrice_${tag}`,
            },
            {
              label: '价格有效期',
              prop: `priceExpireTime_${tag}`,
            },
            {
              label: '异常类型',
              render: (h, { row }) => {
                if (row[`priceExpReasonList_${tag}`] && row[`priceExpReasonList_${tag}`].length) {
                  return <span style="color: red">{row[`priceExpReasonList_${tag}`].map(item => item.approvalTypeTemplate).join('，')}</span>
                }
              }
            },
            {
              label: '异常原因',
              prop: `priceExpType_${tag}`,
              render: (h, { row }) => {
                if (!row[`priceExpReasonList_${tag}`]) {
                  return ''
                }
                return <el-popover
                  placement="right"
                  width="600"
                  trigger="hover">
                  <el-table border data={row[`priceExpReasonList_${tag}`]}>
                    <el-table-column property="approvalTypeTemplate" label="异常类型"></el-table-column>
                    <el-table-column property="concreteExpCause" label="异常原因"></el-table-column>
                    <el-table-column property="content" label="原因说明"></el-table-column>
                  </el-table>
                  <a slot="reference">查看</a>
                </el-popover>
              }
            },
            {
              label: '推荐供应商代码',
              prop: `recommendSupplierCode_${tag}`,
              width: 130
            },
            {
              label: '推荐供应商名称',
              prop: `recommendSupplierName_${tag}`,
              width: 150
            },
            {
              label: '落实到货时间',
              prop: `workableArrivalTime_${tag}`,
              width: 150
            },
          ]
        });
      }
    },
    summaryMethod ({ columns, data }) {
      const summaryList = ['unitPrice', 'costPrice', 'skuPrice', 'productCenterPrice', 'productCenterCostPrice']
      const means = [] // 合计
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push('合计')
        } else if (column.property && summaryList.includes(column.property.split('_')[0])) {
          const values = data.map(item => Number(item[column.property]));
          // 合计
          if (!values.every(value => isNaN(value))) {
            means[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            means[columnIndex] = '<span style="font-weight: bold;">' + toFixedCustomize(means[columnIndex]) + '元</span>'
          } else {
            means[columnIndex] = '';
          }
        }
      })
      return [means]
    }
  }
};
</script>
<style lang="less" scoped>
.user-info {
  font-weight: bold;
  margin: 10px 0;
}
.table-header {
  margin-bottom: 5px;
  .el-button {
    margin-right: 3px;
  }
}
.active {
  border: 1px dashed red;
  border-radius: 4px;
  /deep/ input {
    border: none;
  }
}
</style>
